package me.zhengjie.modules.finace_taxation.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import me.zhengjie.base.PageInfo;
import me.zhengjie.base.QueryHelpMybatisPlus;
import me.zhengjie.modules.finace_taxation.domain.FtFeedback;
import me.zhengjie.modules.finace_taxation.domain.FtLiveBroadcast;
import me.zhengjie.utils.ConvertUtil;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.modules.finace_taxation.domain.FtUsers;
import me.zhengjie.modules.finace_taxation.service.FtUsersService;
import me.zhengjie.modules.finace_taxation.service.dto.FtUsersDto;
import me.zhengjie.modules.finace_taxation.service.dto.FtUsersQueryParam;
import me.zhengjie.modules.finace_taxation.service.mapper.FtUsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
* @author 杨荣森
* @date 2021-06-28
*/
@Service
//@AllArgsConstructor
// @CacheConfig(cacheNames = FtUsersService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class FtUsersServiceImpl implements FtUsersService {

    // private final RedisUtils redisUtils;
    @Autowired
    private FtUsersMapper ftUsersMapper;

    @Autowired
    private RestTemplate restTemplate;

    private String WXLOGIN_URI = "https://api.weixin.qq.com/sns/jscode2session?appid=wx6a1433411d4e4b2a&secret=a6d50931dee8b8db7193f1370dea7340&grant_type=authorization_code&js_code=";


    @Override
    public PageInfo<FtUsersDto> queryAll(FtUsersQueryParam query, Pageable pageable) {
        QueryWrapper<FtUsers> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(FtUsers::getNickName, query.getNickName());
        IPage<FtUsers> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<FtUsers> page = ftUsersMapper.selectPage(queryPage, QueryHelpMybatisPlus.getPredicate(query));
        return ConvertUtil.convertPage(page, FtUsersDto.class);
    }

    @Override
    public List<FtUsersDto> queryAll(FtUsersQueryParam query){
        QueryWrapper<FtUsers> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(FtUsers::getNickName, query.getNickName());
        return ConvertUtil.convertList(ftUsersMapper.selectList(QueryHelpMybatisPlus.getPredicate(query)), FtUsersDto.class);
    }

    @Override
    public FtUsers getById(String id) {
        return ftUsersMapper.selectById(id);
    }

    @Override
    // @Cacheable(key = "'id:' + #p0")
    public FtUsersDto findById(String id) {
        return ConvertUtil.convert(getById(id), FtUsersDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(FtUsersDto resources) {
        FtUsers entity = ConvertUtil.convert(resources, FtUsers.class);
        return ftUsersMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateById(FtUsersDto resources){
        FtUsers entity = ConvertUtil.convert(resources, FtUsers.class);
        int ret = ftUsersMapper.updateById(entity);
        // delCaches(resources.id);
        return ret;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeByIds(Set<String> ids){
        // delCaches(ids);
        return ftUsersMapper.deleteBatchIds(ids);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeById(String id){
        Set<String> set = new HashSet<>(1);
        set.add(id);
        return this.removeByIds(set);
    }

    @Override
    public int updateAvatar(FtUsers ftUsers) {
        return ftUsersMapper.updateById(ftUsers);
    }

    @Override
    public FtUsers findByPhone(String phone) {
        QueryWrapper<FtUsers> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(FtUsers::getPhoneNumber, phone);
        FtUsers ftUsers = ftUsersMapper.selectOne(wrapper);
        return ftUsers;
    }

    @Override
    public int updateByPhone(FtUsers ftUsers) {
        return ftUsersMapper.updateById(ftUsers);
    }

    @Override
    public int updatePwd(FtUsers ftUsers) {
        return ftUsersMapper.updateById(ftUsers);
    }

    @Override
    public JSONObject WXLogin(FtUsersDto ftUsersDto) {
        JSONObject jsonObject = new JSONObject();
        try {
            String QQResult = restTemplate.getForObject(this.WXLOGIN_URI + ftUsersDto.getCode(), String.class);
            FtUsers ftUsers = JSON.parseObject(JSON.parse(QQResult).toString(), FtUsers.class);
            ftUsers.setAvatarUrl(ftUsersDto.getAvatarUrl());
            ftUsers.setCity(ftUsersDto.getCity());
            ftUsers.setCountry(ftUsersDto.getCountry());
            ftUsers.setGender(ftUsersDto.getGender());
            ftUsers.setNickName(ftUsersDto.getNickName());
            int count = ftUsersMapper.getFtUserByWXOpenid(ftUsers.getOpenid());
            if (count == 0) {
                //新用户注册
                ftUsersMapper.insert(ftUsers);
                jsonObject.put("code",202);
                jsonObject.put("message","新用户注册");
            }else {
                jsonObject.put("message","老用户");;
                jsonObject.put("code",200);
            }
            //通过openId查询用户信息
            FtUsers userStorage = ftUsersMapper.getFtUserByopenid(ftUsers.getOpenid());
            jsonObject.put("result",userStorage);
            jsonObject.put("success",true);
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.put("message","服务器响应失败");
            jsonObject.put("code","500");
            jsonObject.put("success",false);
            return jsonObject;
        }
    }

    /*
    private void delCaches(String id) {
        redisUtils.delByKey(CACHE_KEY + "::id:", id);
    }

    private void delCaches(Set<String> ids) {
        for (String id: ids) {
            delCaches(id);
        }
    }*/

    @Override
    public void download(List<FtUsersDto> all, HttpServletResponse response) throws IOException {
      List<Map<String, Object>> list = new ArrayList<>();
      for (FtUsersDto ftUsers : all) {
        Map<String,Object> map = new LinkedHashMap<>();
              map.put("头像", ftUsers.getAvatarUrl());
              map.put("昵称", ftUsers.getNickName());
              map.put("城市", ftUsers.getCity());
              map.put("国家", ftUsers.getCountry());
              map.put("性别，1.男，2.女，0.未知", ftUsers.getGender());
              map.put("手机号", ftUsers.getPhoneNumber());
        list.add(map);
      }
      FileUtil.downloadExcel(list, response);
    }
}
